﻿using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Peninsula.Common;
using Peninsula.DataAccess.POCO;
using Peninsula.Site.Data.Constant;

namespace Peninsula.Account.Manager
{
    public  class PermissionManager:ManagerBase
    {
        [Inject]
        public ISiteCache SiteCache { get; set; }

        public virtual void Add(Permission permission)
        {
            PermissionProvider.Insert(permission);
        }

        public virtual void Delete(string permissionName)
        {
            PermissionProvider.Delete(p => p.PermissionName == permissionName);
        }

        public virtual void Delete(Expression<Func<Permission, bool>> predicate)
        {
            PermissionProvider.Delete(predicate);
        }

        public virtual Permission Get(string permissionName)
        {
            return PermissionProvider.Get(p => p.PermissionName == permissionName);
        }

        public virtual Permission Get(Expression<Func<Permission, bool>> predicate)
        {
            return PermissionProvider.Get(predicate);
        }

        public virtual IEnumerable<Permission> All()
        {
            return PermissionProvider.Entities;
        }

        public virtual void Update(Permission permission)
        {
            PermissionProvider.Update(permission);
        }

        #region Permissions

        public virtual IEnumerable<Permission> GetAllPermissionsByRoleName(string roleName)
        {
            return RoleProvider.Get(r => r.RoleName == roleName).Permissions.AsEnumerable();
        }

        public virtual IEnumerable<Permission> GetAllPermissionsByAdminName(string userName)
        {
            return AdminProvider.Get(a => a.UserName == userName).Roles.SelectMany(r => r.Permissions).Distinct().AsEnumerable();
        }

        #endregion

        #region Cache
        public virtual List<Permission> GetAllPermissionCache(bool refresh = false)
        {
            return SiteCache.Get(CacheNames.ADMIN_PERMISSIONS, () =>
            {
                return this.All().ToList();
            }, DateTime.Now.AddHours(1) - DateTime.Now, refresh: refresh);
        }
        #endregion
    }
}

